package net.maku.project.job;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.project.entity.InfoEntity;
import net.maku.project.service.InfoService;
import net.maku.sms.service.SmsService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
  @FileName: WeeklyProgressAlerts 0 30 17 ? * FRI 执行 WeeklyProgressAlerts.java 任务类，用于提醒项目周度进展情况
 * @Project: maku-boot-zzhl
 * @Package: net.maku.project.job
 * @Author: Aili
 * @Date: 2024/7/26 14:08
 * @Version: 1.0.0
 * @Description: WeeklyProgressAlerts Description
 */

import org.apache.commons.lang3.StringUtils;

@Slf4j
@Service
@RequiredArgsConstructor
public class WeeklyProgressAlerts {
    private final InfoService infoService;
    private final SmsService smsService;

    public void run() {
        log.info("WeeklyProgressAlerts");

        // 查询本周未完成的任务并过滤
        List<InfoEntity> filteredInfoEntities = infoService.selectUnFinishPorject().stream()
                .filter(info -> StringUtils.isNotBlank(info.getWeeklyProgress()))
                .toList();

        // 遍历过滤后的任务列表，发送短信提醒
        for (InfoEntity infoEntity : filteredInfoEntities) {
            sendWeeklyProgressAlertsSafely(infoEntity);
        }
    }

    private void sendWeeklyProgressAlertsSafely(InfoEntity infoEntity) {
        Map<String, String> params = new HashMap<>();
        params.put("projectName", infoEntity.getProjectName());
        params.put("projectCode", infoEntity.getProjectCode());
        params.put("weeklyProgress", infoEntity.getWeeklyProgress());
        params.put("contact", infoEntity.getContactName());
        params.put("templateId", "E");
        params.put("contactMobile", infoEntity.getContactPhone());

        String mobile = infoEntity.getLinkedLeaderPhone() != null ? infoEntity.getLinkedLeaderPhone().trim() : "";

        // 简化的手机号验证及发送短信逻辑
        if (isValidMobile(mobile)) {
            smsService.send(mobile, params);
        } else {
            log.error("手机号错误，手机号为：" + mobile);
        }
    }

    // 新增手机号验证方法
    private boolean isValidMobile(String mobile) {
        return mobile.length() == 11 && mobile.matches("^1[3456789].d{9}$");
    }
}
